/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    enum Direction {
        ROOT,
        LEFT,
        RIGHT,
    };
    struct Range {
        int left;
        int right;
        Direction dir; // 0:root 1:left 2:right
        TreeNode *parent;
        TreeNode *node;
    };
    TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
        queue<Range> q;
        TreeNode *root = new TreeNode;
        q.push({0, (int)nums.size() - 1, ROOT, NULL, root});
        while (!q.empty()) {
            Range r = q.front();
            q.pop();
            int maxNum = INT_MIN;
            int maxIndex;
            for (int i = r.left; i <= r.right; ++i) {
                if (maxNum < nums[i]) {
                    maxNum = nums[i];
                    maxIndex = i;
                }
            }
            TreeNode *left = NULL;
            TreeNode *right = NULL;
            if (maxIndex > r.left) {
                left = new TreeNode;
                q.push({r.left, maxIndex - 1, LEFT, r.node, left});
            }
            if (maxIndex < r.right) {
                right = new TreeNode;
                q.push({maxIndex + 1, r.right, RIGHT, r.node, right});
            }
            r.node->val = maxNum;
            switch (r.dir) {
                case LEFT:
                    r.parent->left = r.node;
                    break;
                case RIGHT:
                    r.parent->right = r.node;
                    break;
            }
        }
        return root;
    }
};